package com.warm.mini.wework.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author warmchuang
 * @date 2023/12/9 18:06
 * @desc
 */
@Slf4j
public class JsonUtil {
    public static <T> T readJsonFile(String filePath, Class<T> clazz) {
        try{
            InputStream inputStream = new ClassPathResource(filePath).getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return JSON.parseObject(stringBuilder.toString(), clazz);
        } catch (Exception e){
            log.info("read json error:{}", e, e.getMessage());
        }
        return null;
    }

    public static void writeJsonFile(String filePath, JSONObject data) {
        ClassPathResource resource = new ClassPathResource(filePath);
        try (OutputStream outputStream = new FileOutputStream(resource.getFile());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
            String jsonString = JSON.toJSONString(data, true);
            bufferedWriter.write(jsonString);
        } catch (Exception e){
            log.info("read json error:{}", e, e.getMessage());
        }
    }
}
